package cn.tedu.egweibo0618.controller;

import cn.tedu.egweibo0618.base.response.JsonResult;
import cn.tedu.egweibo0618.base.response.StatusCode;
import cn.tedu.egweibo0618.mapper.UserMapper;
import cn.tedu.egweibo0618.pojo.dto.UserLoginParam;
import cn.tedu.egweibo0618.pojo.dto.UserRegParam;
import cn.tedu.egweibo0618.pojo.entity.User;
import cn.tedu.egweibo0618.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@Tag(name = "01用户模块")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @Operation(summary = "用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody UserRegParam userRegParam){
        log.debug("userRegParam:"+ userRegParam);
        String username = userRegParam.getUsername();
        int rows = userMapper.selectByUsername(username);
        if (rows>0){
            return new JsonResult( StatusCode.USERNAME_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }
    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession  session){
        log.debug("userLoginParam:"+ userLoginParam);
        UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }
}
